package foliotracker.GUI;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;

import foliotracker.Portfolio;
import foliotracker.PortfolioCollection;

public class PortfolioCollectionTableModel extends DefaultTableModel implements Observer
{
	private int collectionSize;
	private PortfolioCollection collection;
	private DecimalFormat priceFormat, percentageFormat;
	
	public PortfolioCollectionTableModel(PortfolioCollection collection)
	{
		this.collection = collection;
		setColumnIdentifiers(new Object[] { "Name", "Value", "Total cost", "% Gain" });
		
		priceFormat = new DecimalFormat("£0.00");
		percentageFormat = new DecimalFormat("#.##%");
		collectionSize = collection.getPortfolios().size();
		
		collection.addObserver(this);
		
		for (Portfolio portfolio: collection.getPortfolios())
		{
			addRow(portfolio);
		}
	}
	
	private void addRow(Portfolio portfolio)
	{
		portfolio.addObserver(this);
		
		super.addRow(new Object[] { 
				portfolio.getName(), 
				priceFormat.format(portfolio.getTotalValue()), 
				priceFormat.format(portfolio.getTotalInitialCost()),
				percentageFormat.format(portfolio.getPercentageGain())
			});
	}
	
	@Override
	public boolean isCellEditable(int row, int col)
	{
		return false;
    }
	

	@Override
	public void update(Observable o, Object arg)
	{
		//if the changed object is the portfolioCollection, maybe we've added a portfolio
		if(o instanceof PortfolioCollection)
		{
			PortfolioCollection collection = (PortfolioCollection)o;
			List<Portfolio> portfolios = collection.getPortfolios();
			
			if (portfolios.size() > collectionSize)
			{
				//assume the last in the list was the one added
				Portfolio portfolio = portfolios.get(portfolios.size() - 1);
				addRow(portfolio);
				
				collectionSize = portfolios.size();
			}
			else if (portfolios.size() < collectionSize)
			{
				//removed a portfolio
				collectionSize = portfolios.size();
			}
		}
		else if (o instanceof Portfolio)
		{
			Portfolio portfolio = (Portfolio)o;
			int row = collection.getPortfolios().indexOf(portfolio);
			
			super.setValueAt(portfolio.getName(), row, 0);
			super.setValueAt(priceFormat.format(portfolio.getTotalValue()), row, 1);
			super.setValueAt(priceFormat.format(portfolio.getTotalInitialCost()), row, 2);
			super.setValueAt(percentageFormat.format(portfolio.getPercentageGain()), row, 3);
		}
		
		this.fireTableChanged(new TableModelEvent(this));
	}

}
